import SwiftUI

@available(macOS 12.0, *)
struct ContentView: View {
    @State private var selectedFile: URL?
    @State private var isVideo = false
    @State private var showError = false
    @State private var errorMessage = ""
    @State private var selectedScreen: NSScreen? = NSScreen.main
    @State private var volume: Float = 1.0
    @State private var isMuted = false
    
    // 监听显示器选择变化，同步音量和静音状态
    private func updateAudioState() {
        if let screen = selectedScreen, let state = DisplayManager.shared.getWallpaperState(for: screen) {
            volume = state.volume
            isMuted = state.isMuted
        }
    }
    

    @State private var showResourceLibrary = false
    
    private let defaultImagePath = Bundle.main.url(forResource: "317bf8542f352fc91dce835368bd-2120987", withExtension: "jpg")
    
    init() {
        _selectedFile = State(initialValue: defaultImagePath)
    }
    var body: some View {
        HSplitView {
            
            
            // 右侧主界面
            VStack(spacing: 0) {
                Text("壁纸设置工具")
                    .font(.system(.title, design: .rounded))
                    .padding(.vertical, 16)
                    .frame(maxWidth: .infinity)
                    .background(Color(.windowBackgroundColor))
                
                ScrollView {
                    VStack(spacing: 16) {
                        // 显示器选择
                        GroupBox(label: Text("显示器").font(.headline)) {
                            Picker("选择显示器", selection: $selectedScreen) {
                                ForEach(NSScreen.screens, id: \.self) { screen in
                                    Text("显示器 \((screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? UInt32)?.description ?? "")")
                                        .tag(screen as NSScreen?)
                                }
                            }
                            .pickerStyle(.menu)
                            .padding(.vertical, 8)
                            .onChange(of: selectedScreen) { _ in
                                updateAudioState()
                            }
                        }
                        .padding(.horizontal, 12)
                        
                        // 壁纸预览
                        GroupBox(label: Text("预览").font(.headline)) {
                            VStack(spacing: 16) {
                                WallpaperPreview(wallpaper: selectedFile.map { url in
                                    PeapixWallpaper(
                                        title: url.lastPathComponent,
                                        copyright: "",
                                        date: "",
                                        pageUrl: "",
                                        fullUrl: url,
                                        thumbUrl: url,
                                        imageUrl: url
                                    )
                                }, isVideo: isVideo)
                                    .shadow(radius: 2)
                                
                                Toggle("视频壁纸", isOn: $isVideo)
                                
                                // 视频控制面板
                                if isVideo {
                                    HStack(spacing: 8) {
                                        Image(systemName: isMuted ? "speaker.slash" : "speaker.wave.2")
                                            .foregroundColor(.accentColor)
                                            .onTapGesture {
                                                isMuted.toggle()
                                                if let screen = selectedScreen {
                                                    DisplayManager.shared.toggleMute(for: screen)
                                                }
                                            }
                                        
                                        Slider(value: $volume, in: 0...1) { _ in
                                            if let screen = selectedScreen {
                                                DisplayManager.shared.setVolume(volume, for: screen)
                                            }
                                        }
                                        .frame(maxWidth: .infinity)
                                    }
                                }
                            }
                            .padding(12)
                        }
                        .padding(.horizontal, 12)
                        
                        // 操作按钮
                        GroupBox(label: Text("操作").font(.headline)) {
                            VStack(spacing: 12) {
                                HStack(spacing: 12) {
                                    
                                    
                                    Button("选择文件") {
                                        let panel = NSOpenPanel()
                                        panel.allowedContentTypes = isVideo ? [.mpeg4Movie, .quickTimeMovie] : [.image]
                                        if panel.runModal() == .OK {
                                            selectedFile = panel.url
                                        }
                                    }
                                    .buttonStyle(.bordered)
                                    
                                    Button("资源库") {
                                        showResourceLibrary.toggle()
                                    }
                                    .buttonStyle(.bordered)
                                }
                                
                                HStack(spacing: 12) {

                                    
                                    Button("设置壁纸") {
                                        if let url = selectedFile, let screen = selectedScreen {
                                            do {
                                                try DisplayManager.shared.setWallpaper(url: url, isVideo: isVideo, for: screen)
                                                // 设置壁纸后更新音频状态
                                                if isVideo {
                                                    // 应用当前的静音状态到新设置的壁纸
                                                    if isMuted {
                                                        DisplayManager.shared.toggleMute(for: screen)
                                                    }
                                                    // 应用当前的音量设置
                                                    DisplayManager.shared.setVolume(volume, for: screen)
                                                }
                                                // 更新UI状态以匹配实际壁纸状态
                                                updateAudioState()
                                            } catch {
                                                errorMessage = "设置壁纸失败: \(error.localizedDescription)"
                                                showError = true
                                            }
                                        }
                                    }
                                    .buttonStyle(.borderedProminent)
                                    .disabled(selectedFile == nil || selectedScreen == nil)
                                }
                            }
                            .padding(12)
                        }
                        .padding(.horizontal, 12)
                    }
                    .padding(.vertical)
                }
            }
            .frame(minWidth: 180, minHeight: 680)
        }
        .alert("错误", isPresented: $showError) {
            Button("确定", role: .cancel) {}
        } message: {
            Text(errorMessage)
        }
        .sheet(isPresented: $showResourceLibrary) {
            WallpaperManagementView { url in
                selectedFile = url
                isVideo = (try? url.resourceValues(forKeys: [.contentTypeKey]).contentType)?.conforms(to: .movie) == true
                showResourceLibrary = false
            }
            .frame(minWidth: 500, minHeight: 400)
        }
        .onAppear {
            // 视图出现时同步音频状态
            updateAudioState()
        }
    }
}
